package com.SmartCare.service.impl.moments;

import cn.hutool.core.util.ObjUtil;
import com.SmartCare.common.Result;
import com.SmartCare.common.dto.moments.DynamicInfoDTO;
import com.SmartCare.common.vo.CommentInfoVo;
import com.SmartCare.common.vo.DynamicInfoVo;
import com.SmartCare.mapper.momments.DynamicInfoMapper;
import com.SmartCare.pojo.moments.CommentInfo;
import com.SmartCare.pojo.moments.DynamicInfo;
import com.SmartCare.pojo.moments.ForwardInfo;
import com.SmartCare.pojo.moments.LikeInfo;
import com.SmartCare.pojo.role.ElderlyInformation;
import com.SmartCare.service.moments.CommentInfoService;
import com.SmartCare.service.moments.DynamicInfoService;
import com.SmartCare.service.moments.ForwardInfoService;
import com.SmartCare.service.moments.LikeInfoService;
import com.SmartCare.service.role.ElderlyInformationService;
import com.SmartCare.service.role.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class DynamicInfoServiceImpl extends ServiceImpl<DynamicInfoMapper, DynamicInfo> implements DynamicInfoService {
    @Resource
    private LikeInfoService likeInfoService;
    @Resource
    private ForwardInfoService forwardInfoService;
    @Resource
    private CommentInfoService commentInfoService;
    @Resource
    private ElderlyInformationService elderlyInformationService;

    @Resource
    private UserService userService;

    /**
     * 查询老人所有动态
     *
     * @param homeId        养老院id
     * @param currentUserId 当前请求用户id
     */
    @Override
    public Result getAllDynamic(Long homeId, Long currentUserId) {
        //查询统一养老院的所有老人id
        List<Long> elderIds = elderlyInformationService.getIdsByHomeId(homeId);

        //查询老人的动态
        List<DynamicInfoVo> res = new ArrayList<>();
        elderIds.forEach((item) -> {
            List<DynamicInfoVo> infoVos = getMyDynamic(item, currentUserId);
            res.addAll(infoVos);
        });
        //按照发布时间降序排列
        res.sort(Comparator.comparing(DynamicInfoVo::getCreateTime).reversed());
        return Result.success(res);
    }

    /**
     * @param userId        根据老人id查询动态
     * @param currentUserId 前端传递的老人id用户判断是否点赞
     */
    public List<DynamicInfoVo> getMyDynamic(Long userId, Long currentUserId) {
        //返回的结果
        List<DynamicInfoVo> res = new ArrayList<>();

        //查询动态 动态信息并降序排列
        LambdaUpdateWrapper<DynamicInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DynamicInfo::getUserId, userId);
        wrapper.orderByDesc(DynamicInfo::getCreateTime);
        List<DynamicInfo> list = list(wrapper);

        list.forEach((item) -> {
            DynamicInfoVo vo = new DynamicInfoVo();
            BeanUtils.copyProperties(item, vo);
            //统计该动态点赞数
            long likes = likeInfoService.count(new LambdaQueryWrapper<LikeInfo>().eq(LikeInfo::getDynamicId, item.getId()));
            vo.setLikes(likes);


            LikeInfo one1 = likeInfoService.getOne(new LambdaQueryWrapper<LikeInfo>().eq(LikeInfo::getUserId, currentUserId).eq(LikeInfo::getDynamicId, vo.getId()));
            if (one1 != null) {
                vo.setLikeFlag(one1.getId());
            } else {
                vo.setLikeFlag(-1L);
            }

            //统计该动态的转发数
            long shares = forwardInfoService.count(new LambdaQueryWrapper<ForwardInfo>().eq(ForwardInfo::getDynamicId, item.getId()));
            vo.setForwards(shares);

            //查询该动态对应的老人信息
            ElderlyInformation one = elderlyInformationService.getById(item.getUserId());
            if(ObjUtil.isNotEmpty(one)){
                vo.setName(one.getElderlyName());
                vo.setIconUrl(one.getIconUrl());
            }

            //统计并分封装该动态对应的评论信息
            List<CommentInfoVo> commentInfoVos = new ArrayList<>();
            LambdaQueryWrapper<CommentInfo> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.orderByDesc(CommentInfo::getCreateTime);
            wrapper1.eq(CommentInfo::getDynamicId, item.getId());
            List<CommentInfo> commentInfos = commentInfoService.list(wrapper1);

            commentInfos.forEach((item2) -> {
                CommentInfoVo vo1 = new CommentInfoVo();
                String name = elderlyInformationService.getNameById(item2.getUserId());
                BeanUtils.copyProperties(item2, vo1, "name");
                vo1.setName(name);
                commentInfoVos.add(vo1);
            });
            vo.setComments(commentInfoVos);
            res.add(vo);
        });

        return res;
    }

    //查看本用户动态
    @Override
    public List<DynamicInfoVo> getMyDynamic(Long userId) {
        //返回的结果
        List<DynamicInfoVo> res = new ArrayList<>();

        //查询动态 动态信息并降序排列
        LambdaUpdateWrapper<DynamicInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DynamicInfo::getUserId, userId);
        wrapper.orderByDesc(DynamicInfo::getCreateTime);
        List<DynamicInfo> list = list(wrapper);

        list.forEach((item) -> {
            DynamicInfoVo vo = new DynamicInfoVo();
            BeanUtils.copyProperties(item, vo);
            //统计该动态点赞数
            long likes = likeInfoService.count(new LambdaQueryWrapper<LikeInfo>().eq(LikeInfo::getDynamicId, item.getId()));
            vo.setLikes(likes);

            LikeInfo one1 = likeInfoService.getOne(new LambdaQueryWrapper<LikeInfo>().eq(LikeInfo::getUserId, userId).eq(LikeInfo::getDynamicId, vo.getId()));
            if (one1 != null) {
                vo.setLikeFlag(one1.getId());
            } else {
                vo.setLikeFlag(-1L);
            }

            //统计该动态的转发数
            long shares = forwardInfoService.count(new LambdaQueryWrapper<ForwardInfo>().eq(ForwardInfo::getDynamicId, item.getId()));
            vo.setForwards(shares);

            //查询该动态对应的老人信息
            ElderlyInformation one = elderlyInformationService.getById(item.getUserId());
            if(ObjUtil.isNotEmpty(one)){
                vo.setName(one.getElderlyName());
                vo.setIconUrl(one.getIconUrl());
            }

            //统计并分封装该动态对应的评论信息
            List<CommentInfoVo> commentInfoVos = new ArrayList<>();
            LambdaQueryWrapper<CommentInfo> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.orderByDesc(CommentInfo::getCreateTime);
            wrapper1.eq(CommentInfo::getDynamicId, item.getId());
            List<CommentInfo> commentInfos = commentInfoService.list(wrapper1);

            commentInfos.forEach((item2) -> {
                CommentInfoVo vo1 = new CommentInfoVo();
                String name = elderlyInformationService.getNameById(item2.getUserId());
                BeanUtils.copyProperties(item2, vo1, "name");
                vo1.setName(name);
                commentInfoVos.add(vo1);
            });
            vo.setComments(commentInfoVos);
            res.add(vo);
        });

        return res;
    }

    /**
     * 将老友圈信息转成vo类型
     *
     * @param list   要进行转换的老友圈信息列表
     * @param userId 当前使用的用户id，用于获取点赞信息
     * @return 返回转换后的vo列表
     */
    public List<DynamicInfoVo> transToVo(List<DynamicInfo> list, Long userId) {
        if (list.size() == 0) {
            return new ArrayList<>();
        }
        //返回的结果
        List<DynamicInfoVo> res = new ArrayList<>();

        list.forEach((item) -> {
            DynamicInfoVo vo = new DynamicInfoVo();
            BeanUtils.copyProperties(item, vo);
            //统计该动态点赞数
            long likes = likeInfoService.count(new LambdaQueryWrapper<LikeInfo>().eq(LikeInfo::getDynamicId, item.getId()));
            vo.setLikes(likes);

            LikeInfo one1 = likeInfoService.getOne(new LambdaQueryWrapper<LikeInfo>().eq(LikeInfo::getUserId, userId).eq(LikeInfo::getDynamicId, vo.getId()));
            if (one1 != null) {
                vo.setLikeFlag(one1.getId());
            } else {
                vo.setLikeFlag(-1L);
            }

            //统计该动态的转发数
            long shares = forwardInfoService.count(new LambdaQueryWrapper<ForwardInfo>().eq(ForwardInfo::getDynamicId, item.getId()));
            vo.setForwards(shares);

            //查询该动态对应的老人信息
            ElderlyInformation one = elderlyInformationService.getById(item.getUserId());
            if(ObjUtil.isNotEmpty(one)){
                vo.setName(one.getElderlyName());
                vo.setIconUrl(one.getIconUrl());
            }

            //统计并分封装该动态对应的评论信息
            List<CommentInfoVo> commentInfoVos = new ArrayList<>();
            LambdaQueryWrapper<CommentInfo> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.orderByDesc(CommentInfo::getCreateTime);
            wrapper1.eq(CommentInfo::getDynamicId, item.getId());
            List<CommentInfo> commentInfos = commentInfoService.list(wrapper1);

            commentInfos.forEach((item2) -> {
                CommentInfoVo vo1 = new CommentInfoVo();
                String name = elderlyInformationService.getNameById(item2.getUserId());
                BeanUtils.copyProperties(item2, vo1, "name");
                vo1.setName(name);
                commentInfoVos.add(vo1);
            });
            vo.setComments(commentInfoVos);
            res.add(vo);
        });

        return res;
    }

    @Override
    public Result deleteDynamic(Long id) {
        if (id == null) {
            return Result.error("请先登录");
        }
        boolean res = this.removeById(id);
        if (res) {
            return Result.success();
        }
        return Result.error("未知错误");
    }

    @Override
    public Result publishDynamic(DynamicInfoDTO dynamic) {
        if (dynamic.getUserId() == null) {
            return Result.error("请先登录");
        }

        DynamicInfo info = new DynamicInfo();
        BeanUtils.copyProperties(dynamic, info);
        boolean res = save(info);
        if (res) {
            return Result.success();
        }
        return Result.error("未知错误");
    }

    //更新动态
    @Override
    public Result updateDynamic(Long id, DynamicInfoDTO dynamic) {

        LambdaUpdateWrapper<DynamicInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DynamicInfo::getId, id);
        wrapper.set(DynamicInfo::getUserId, dynamic.getUserId());
        wrapper.set(DynamicInfo::getContent, dynamic.getContent());
        wrapper.set(DynamicInfo::getImageUrl, dynamic.getImageUrl());
        wrapper.set(DynamicInfo::getUpdateTime, LocalDateTime.now());
        boolean res = update(wrapper);
        if (res) {
            return Result.success();
        }
        return Result.error("未知错误");
    }

    @Override
    public Result getPage(Integer page, Integer pageSize, String careHomeName, Long userId) {
        // 获取该养老院的所有用户id
        List<Long> ids = userService.getIdsByCHName(careHomeName);
        // 获取该养老院所有老友圈数据
        QueryWrapper<DynamicInfo> qw = new QueryWrapper<>();
        qw.in("user_id", ids);
        // 按发布时间降序排序
        qw.orderByDesc("create_time");
        // 获取分页数据
        IPage<DynamicInfo> iPage = new Page<>(page, pageSize);
        IPage<DynamicInfo> pageData = page(iPage, qw);
        // 将分页数据转换成vo
        List<DynamicInfo> records = pageData.getRecords();
        List<DynamicInfoVo> vos = transToVo(records, userId);

        return Result.success(vos);
    }
}
